package com.pengke.pangu.auth;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.stp.StpInterface;
import com.pengke.pangu.common.config.ConstConfig;
import com.pengke.pangu.service.sys.entity.SysPermission;
import com.pengke.pangu.service.sys.entity.SysRole;
import com.pengke.pangu.service.sys.service.ISysPermissionService;
import com.pengke.pangu.service.sys.service.ISysRoleService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 自定义权限认证接口扩展，Sa-Token 将从此实现类获取每个账号拥有的权限码
 *
 * @author lijunjie
 */
@Slf4j
@Component
public class StpInterfaceImpl implements StpInterface {

    @Resource
    private ISysPermissionService sysPermissionService;

    @Resource
    private ISysRoleService sysRoleService;
    /**
     * 返回一个账号所拥有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        // 1. 声明权限码集合
        List<String> list = new ArrayList<>();

        // 2. 遍历角色列表，查询拥有的权限码
        for (String roleCode : getRoleList(loginId, loginType)) {
            List<String> permissionList = (List<String>)SaManager.getSaTokenDao().getObject(ConstConfig.SATOKEN_REDIS_KEY_ROLE_PERMISSION + roleCode);
            if(permissionList == null) {
                List<SysPermission> sysPermissionList = sysPermissionService.getSysPermissionByRoleCode(roleCode);
                if (!sysPermissionList.isEmpty()){
                    permissionList = new ArrayList<>();
                    for(SysPermission sysPermission : sysPermissionList){
                        permissionList.add(sysPermission.getPermissionCode());
                    }
                }
                // 查好后，set 到缓存中
                SaManager.getSaTokenDao().setObject(ConstConfig.SATOKEN_REDIS_KEY_ROLE_PERMISSION + roleCode, permissionList, 60 * 60 * 24 * 30);
            }
            if (permissionList != null) {
                list.addAll(permissionList);
            }
        }
        return list;
    }

    /**
     * 返回一个账号所拥有的角色标识集合
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        List<String> roleList = (List<String>) SaManager.getSaTokenDao().getObject(ConstConfig.SATOKEN_REDIS_KEY_LOGIN_ROLE + loginId);
        if(roleList == null){
            List<SysRole> sysRoleList = sysRoleService.getRoleByUserId(Integer.parseInt(loginId.toString()));
            if (!sysRoleList.isEmpty()){
                roleList = new ArrayList<>();
                for (SysRole sysRole : sysRoleList){
                    roleList.add(sysRole.getRoleCode());
                }
                SaManager.getSaTokenDao().setObject(ConstConfig.SATOKEN_REDIS_KEY_LOGIN_ROLE + loginId, roleList, 60 * 60 * 24 * 30);
            }
        }
        return roleList;
    }
}
